<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="优惠券名称" prop="name" label-width="100px">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入优惠券名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="优惠金额" prop="saleMoney">
        <el-input
          v-model="queryParams.saleMoney"
          placeholder="请输入优惠金额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="可用开始时间" prop="startTime" label-width="100px">
        <el-time-select clearable
                        v-model="queryParams.startTime"
                        placeholder="请选择可用开始时间"
                        :picker-options="{
                            start: '08:30',
                            step: '00:15',
                            end: '18:30'
                          }">
          >
        </el-time-select>
      </el-form-item>
      <el-form-item label="可用结束时间" prop="endTime" label-width="100px">
        <el-time-select clearable
                        v-model="queryParams.endTime"
                        placeholder="请选择可用结束时间"
                        :picker-options="{
                          start: '08:30',
                          step: '00:15',
                          end: '18:30'
                        }">
          >
        </el-time-select>
      </el-form-item>
      <el-form-item label="请选择状态" prop="status" label-width="100px">
        <el-select v-model="queryParams.status" placeholder="请选择状态">
          <el-option label="失效" :value="0"></el-option>
          <el-option label="未失效" :value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"  icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['admin:manage:grant:addCoupon']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['admin:manage:grant:updateCoupon']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['admin:manage:coupon:delCoupon']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['admin:manage:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-set-up"
          size="mini"
          @click="grantCoupon"
          v-hasPermi="['admin:manage:export']"
        >发布优惠券
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-set-up"
          size="mini"
          @click="couponExchangetanchaung"
          v-hasPermi="['admin:manage:export']"
        >券码历史列表
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="manageList" @selection-change="handleSelectionChange">
      <el-table-column  type="selection" width="55" align="center"/>
      <el-table-column fixed label="序号" align="center" prop="id"/>
      <el-table-column label="优惠券名称" align="center" prop="name"/>
      <el-table-column label="类型" align="center" prop="type">
        <template slot-scope="scope">
          <el-tag type="primary" v-if="scope.row.type == 1">打折</el-tag>
          <el-tag type="success" v-if="scope.row.type == 2" >满减</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="上下架状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag type="primary" v-if="scope.row.status == 0" effect="dark">上架</el-tag>
          <el-tag type="success" v-if="scope.row.status == 1" effect="dark">下架</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="优惠金额" align="center" prop="saleMoney"></el-table-column>
      <el-table-column label="折扣" align="center" prop="sale"></el-table-column>
      <el-table-column label="满" align="center" prop="max"></el-table-column>
      <el-table-column label="减" align="center" prop="min"></el-table-column>
      <el-table-column label="可用开始时间" align="center" prop="startTime" width="180"></el-table-column>
      <el-table-column label="可用结束时间" align="center" prop="endTime" width="180"></el-table-column>
      <el-table-column label="可用车型" align="center" prop="carType">
        <template slot-scope="scope">
          <el-tag type="primary" v-if="scope.row.carType == 1" effect="plain">一口价</el-tag>
          <el-tag type="primary" v-if="scope.row.carType == 2" effect="plain">经济型</el-tag>
          <el-tag type="primary" v-if="scope.row.carType == 3" effect="plain">特快车</el-tag>
          <el-tag type="primary" v-if="scope.row.carType == 4" effect="plain">出租车</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="有效期" align="center" prop="endValidTime" width="180">
        <template slot-scope="scope">
          <span> {{ scope.row.endValidTime == null ? '' : scope.row.endValidTime | format('yyyy-MM-dd hh:mm:ss') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span> {{ scope.row.createTime == null ? '' : scope.row.createTime | format('yyyy-MM-dd hh:mm:ss') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span> {{ scope.row.updateTime == null ? '' : scope.row.updateTime | format('yyyy-MM-dd hh:mm:ss') }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['admin:manage:grant:updateCoupon']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['admin:manage:coupon:delCoupon']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!--    券码发布历史列表弹窗-->
    <el-dialog :title="titles" :visible.sync="opens" width="1200px"  append-to-body>
      <el-table v-loading="loading" :data="exchangesLists" @selection-change="handleSelectionChange">
        <el-table-column  type="selection" width="55" align="center"/>
        <el-table-column label="序号" align="center" prop="id"/>
        <el-table-column label="券码" align="center" prop="couponCode"/>
        <el-table-column label="剩余兑换优惠券个数" align="center" prop="remainderNum"/>
        <el-table-column label="可兑换优惠券个数" align="center" prop="allNum"/>
        <!--        <el-table-column label="减" align="center" prop="min"></el-table-column>-->
        <el-table-column label="开始时间" align="center" prop="startTime" width="180">
          <template slot-scope="scope">
            <span> {{ scope.row.startTime == null ? '' : scope.row.startTime | format('yyyy-MM-dd hh:mm:ss') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束时间" align="center" prop="endTime" width="180">
          <template slot-scope="scope">
            <span> {{ scope.row.endTime == null ? '' : scope.row.endTime | format('yyyy-MM-dd hh:mm:ss') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span> {{ scope.row.createTime == null ? '' : scope.row.createTime | format('yyyy-MM-dd hh:mm:ss') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
          <template slot-scope="scope">
            <span> {{ scope.row.updateTime == null ? '' : scope.row.updateTime | format('yyyy-MM-dd hh:mm:ss') }}</span>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="exchangetotal>0"
        :total="exchangetotal"
        :page.sync="couponExchangeParams.pageNum"
        :limit.sync="couponExchangeParams.pageSize"
        @pagination="couponExchangeList"
      />
    </el-dialog>

    <!-- 添加或修改优惠券模块-优惠券对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-scrollbar style="height: 600px;">
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-form-item label="优惠券名称" prop="name">
            <el-input v-model="form.name" style="width: 350px" placeholder="请输入优惠券名称"/>
          </el-form-item>
          <el-form-item label="优惠券类型" prop="type">
            <el-radio-group v-model="form.type">
              <el-radio :label="1">打折</el-radio>
              <el-radio :label="2">满减</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio :label="0">上架</el-radio>
              <el-radio :label="1">下架</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="优惠金额" prop="saleMoney">
            <el-input v-model="form.saleMoney" style="width: 350px" placeholder="请输入优惠金额"/>
          </el-form-item>
          <el-form-item label="折扣" prop="sale">
            <el-input v-model="form.sale" style="width: 350px" placeholder="请输入折扣"/>
          </el-form-item>
          <el-form-item label="满" prop="max">
            <el-input v-model="form.max" style="width: 350px" placeholder="请输入满"/>
          </el-form-item>
          <el-form-item label="减" prop="min">
            <el-input v-model="form.min" style="width: 350px" placeholder="请输入减"/>
          </el-form-item>
          <el-form-item label="可用车型">
            <el-select v-model="form.carType" placeholder="请选择可用车型">
              <el-option
                v-for="item in carList"
                :key="item.type"
                :label="item.name"
                :value="item.type">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="可用开始时间" prop="startTime">
            <el-time-select clearable
                            v-model="form.startTime"
                            placeholder="请选择可用开始时间"
                            :picker-options="{
                            start: '08:30',
                            step: '00:15',
                            end: '18:30'
                          }">
              >
            </el-time-select>
          </el-form-item>
          <el-form-item label="可用结束时间" prop="endTime">
            <el-time-select clearable
                            v-model="form.endTime"
                            placeholder="请选择可用开始时间"
                            :picker-options="{
                              start: '08:30',
                              step: '00:15',
                              end: '11:00'
                            }">
              >
            </el-time-select>
          </el-form-item>
          <el-form-item label="有效期" prop="endValidTime">
            <el-date-picker clearable
                            v-model="form.endValidTime"
                            type="datetime"
                            value-format="yyyy-MM-dd hh:mm:ss"
                            placeholder="请选择有效期"
            >
            </el-date-picker>
          </el-form-item>
        </el-form>
      </el-scrollbar>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary"  @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--    发布优惠券对话框-->
    <el-dialog  :title="title" :visible.sync="openTwo" width="500px" append-to-body>
      <el-form ref="form" :model="ruleForm" :rules="rulesTwo"  label-width="120px">
        <el-form-item label="兑换码" prop="code">
          <el-input v-model="ruleForm.code" style="width: 250px" placeholder="请输入兑换码"/>
        </el-form-item>
        <el-form-item label="优惠券" >
          <el-select v-model="ruleForm.couponId" placeholder="请选择优惠券">
            <el-option
              v-for="item in couponList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="优惠券数量" prop="num">
          <el-input v-model="ruleForm.num" style="width: 250px" placeholder="优惠券数量"/>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker clearable
                          v-model="ruleForm.endTime"
                          type="datetime"
                          value-format="yyyy-MM-dd hh:mm:ss"
                          placeholder="结束时间"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary"  @click="submitCouponGrantVo">确认发布</el-button>
        <el-button @click="cancels">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  couponListManage,
  couponGetManage,
  couponDelManage,
  couponAddManage,
  couponUpdateManage,
  grantCouponManage,
  couponSelectListManage,
  carSelectListManage,
  couponExchangeListManage
} from '@/api/admin/manage'

export default {
  name: 'Manage',
  data() {
    return {
      newDate:new Date(),
      endTimeCoupon:new Date(),
      //发布优惠券
      openTwo: false,
      ruleForm: {
        code: null,
        couponId: null,
        num: null,
        endTime: null
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 券码发布列表总条数
      exchangetotal:0,
      // 优惠券模块-优惠券表格数据
      manageList: [],
      //优惠券列表展示
      couponList:[],
      //券码历史列表
      exchangesLists:[],
      //车型列表展示
      carList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      titles:"",
      opens:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        type: null,
        status: null,
        saleMoney: null,
        sale: null,
        max: null,
        min: null,
        startTime: '',
        endTime: '',
        carType: null,
        isDelete: null
      },
      //券码参数
      couponExchangeParams:{
        pageNum: 1,
        pageSize: 10,
        id: null,
        userId: null,
        couponId: null,
        couponCode: null,
        remainderNum: null,
        allNum: null,
        startTime: '',
        endTime: '',
        updateTime: null,
        createTime: null,
        isDelete: null
      },
      // 表单参数
      form: {},
      rulesTwo: {
        couponId: [
          { required: true, message: '请输入!!!', trigger: 'blur' }
        ],
        num: [
          { required: true,  message: '优惠券不能为空'},
        ],
        endTime: [
          { required: true, message: '请选择时间', trigger: 'blur' }
        ]
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: '请输入优惠券名称', trigger: 'blur' },
          { min: 0, max: 20, message: '长度在 0 到 20 个字符', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
        type: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ],
        saleMoney: [
          { required: true, message: '请输入优惠券金额', trigger: 'blur' }
        ],
        startTime: [
          { required: true, message: '请选择日期', trigger: 'change' }
        ],
        endTime: [
          { required: true, message: '请选择时间', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.couponSelectList();
    this.carSelectList();
    this.couponExchangeList();
  },
  filters: {
    format(value, arg) {
      function dateFormat(date, format) {
        if (typeof date === 'string') {
          var mts = date.match(/(\/Date\((\d+)\)\/)/)
          if (mts && mts.length >= 3) {
            date = parseInt(mts[2])
          }
        }
        date = new Date(date)
        if (!date || date.toUTCString() == 'Invalid Date') {
          return ''
        }
        var map = {
          'M': date.getMonth() + 1, //月份
          'd': date.getDate(), //日
          'h': date.getHours(), //小时
          'm': date.getMinutes(), //分
          's': date.getSeconds(), //秒
          'q': Math.floor((date.getMonth() + 3) / 3), //季度
          'S': date.getMilliseconds() //毫秒
        }
        format = format.replace(/([yMdhmsqS])+/g, function(all, t) {
          var v = map[t]
          if (v !== undefined) {
            if (all.length > 1) {
              v = '0' + v
              v = v.substr(v.length - 2)
            }
            return v
          } else if (t === 'y') {
            return (date.getFullYear() + '').substr(4 - all.length)
          }
          return all
        })
        return format
      }

      return dateFormat(value, arg)

    }
  },

  methods: {

    carSelectList() {
      carSelectListManage().then(response => {
        this.carList = response.data
      })
    },
    grantCoupon() {
      this.resetTwo()
      this.title = '发布优惠券'
      this.openTwo = true
    },

    couponExchangetanchaung(){
      this.titles="券码发布历史列表";
      this.opens=true;
    },
    /**
     * 券码发布列表
     */
    couponExchangeList(){
      this.loading = true
      couponExchangeListManage(this.couponExchangeParams).then(response => {
        this.exchangesLists = response.rows
        this.exchangetotal = response.total
        this.loading = false
      })
    },
    /** 查询优惠券模块-优惠券列表 */
    getList() {
      this.loading = true
      couponListManage(this.queryParams).then(response => {
        this.manageList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    couponSelectList(){
      couponSelectListManage().then(response => {
        this.couponList = response.data
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    cancels() {
      this.openTwo = false
      this.resetTwo()
    },
    resetTwo() {
      this.ruleForm = {
        code: null,
        couponId: null,
        num: null,
        endTime: null
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        type: null,
        status: null,
        saleMoney: null,
        sale: null,
        max: null,
        min: null,
        startTime: null,
        endTime: null,
        carType: null,
        updateTime: null,
        createTime: null,
        isDelete: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加优惠券'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      couponGetManage(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改优惠券'
        this.form.updateTime=new Date().toLocaleTimeString();
      })
    },
    // 发布优惠券提交按钮
    submitCouponGrantVo() {
      const date1 = new Date(this.newDate).getTime();
      const date2 = new Date(this.ruleForm.endTime).getTime();
      if (date2>date1 == true){
        grantCouponManage(this.ruleForm).then(response => {
          this.$modal.msgSuccess('发布成功')
          this.openTwo = false
          this.couponExchangeList();
        })
      }else {
        this.$modal.alertError("请选择大于当前时间!!!")
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            couponUpdateManage(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            couponAddManage(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除优惠券模块-优惠券编号为"' + ids + '"的数据项？').then(function() {
        return couponDelManage(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('admin/manage/coupon/export', {
        ...this.queryParams
      }, `优惠券_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
